#include "server.h"
#include "../../log.h"



Server::Server(boost::asio::io_context&ioc, uint16_t port)
:m_ioc(ioc)
,m_acceptor(ioc, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))
{
    _StartAccetp();
    log_debug("server start listening on port: {}", port);
}
void Server::DeleteSession(const std::string& uuid)
{
    std::unique_lock<std::mutex> lock(m_mutex);
    auto it = m_sessions.find(uuid);
    if(it == m_sessions.end())
    {
        return;
    }
    m_sessions.erase(it);
}

//使用智能指针解决程序崩溃问题
void Server::_StartAccetp()
{
    auto session = std::make_shared<Session>(m_ioc, this);
    m_acceptor.async_accept(session->GetSocket(), 
    [this, session](const boost::system::error_code& ec){
        _HandleAccept(session, ec);
    });
}
void Server::_HandleAccept(std::shared_ptr<Session> session, const boost::system::error_code& ec)
{
    if(ec)
    {
        log_error("Server::_HandleAccept error, code: {}, message: {}", ec.value(), ec.message());
        _StartAccetp();
        return;
    }

    {
        std::unique_lock<std::mutex> lock(m_mutex);
        m_sessions.insert(std::make_pair(session->GetUuid(), session));
    }
    session->Start();
    _StartAccetp();
}